/** ************************* Keywords ********************************* */
var SERVER_ACTION_KEYWORD = "json/keyword/";
var Keywords = [ {
	priority : "",
	keyword : ""
} ];

function NewKeyword(priority, keyword) {
	this.id = id_client.id;
	this.priority = priority;
	this.keyword = keyword;
}

function UpdateKeyword(old_keyword, priority, keyword) {
	this.id = id_client.id;
	this.oldKeyword = old_keyword;
	this.priority = priority;
	this.keyword = keyword;
}

function DeleteKeyword(keyword) {
	this.id = id_client.id;
	this.keyword = keyword;
}


// returns keyword with that priority
function getKeywordByPriority(priority){
	return Keywords[priority-1].keyword;
}
// returns keyword with that priority
function getPriorityByKeyword(keyword){
	for ( var i = 0; i < Keywords.length; i++) {
		if (Keywords[i].keyword == keyword) return Keywords[i].priority;
	} 
	return null;
}


// within this function we use HTTP GET request to get keywords from server
// format of the message should be following {“id”:”user’s id”}
// response received from server is [{“priority”: “keyword’s
// priority”,“keyword”:”extracted keyword”}]
// message gets parsed and values are stored in global variable keywords

function receiveKeywords() {
	var server = serverDomain + SERVER_ACTION_KEYWORD + id_client.id; // server's
																// address
	var xmlHttpReq = getXMLHttpReqObject();
	xmlHttpReq.onreadystatechange = function() {
		if (xmlHttpReq.readyState == 4) {
			if (xmlHttpReq.status == 200) {
				if(!isItFirstTime()){
					Keywords = jsonToObject(xmlHttpReq.responseText);
					showKeywords();
				}
			} else
				errorKeyword(xmlHttpReq);
		}

	};
	xmlHttpReq.open("GET", server, true);
	xmlHttpReq.setRequestHeader('Content-Type',
			'application/json; charset=UTF-8');
	xmlHttpReq.send();
}

function sortKeywords() {
	Keywords.sort(sortRulePriority);
	sendCommandToHippo("keywords");
}

function sortRulePriority(a, b) {
	if (a.priority < b.priority)
		return -1;
	if (a.priority > b.priority)
		return 1;
	return 0;
}

function arrangeKeywords(prior, funk) {
	for ( var i = 0; i < Keywords.length; i++) {
		var keyword = Keywords[i];
		if (keyword.priority >= prior) {
			keyword.priority = funk(keyword.priority);
		}
	}
}

function addNewKeyword(priority, keyword) {
	arrangeKeywords(priority, function(prior) {
		var newPrior = parseInt(prior) + 1;
		return newPrior.toString();
	});
	Keywords.push( {
		priority : priority,
		keyword : keyword
	});
	var message = objectToJson(new NewKeyword(priority, keyword));
	addNewKeywordOnServer(message);
}

// function check to see if new keyword is properly defined
// returns true if is
function isItOk(priority, keyword, oldKeyword) {
	var return_value = false;
	var error_message = "Krk!";
	var editing = false;
	if (oldKeyword != undefined) editing = true;
	if (notOverEight(priority))
		if (areThereDoubles(keyword, oldKeyword))
			if (isPriorityInOrder(priority, editing))
				return_value = true;
			else
				error_message = "priorities must be in order!";
		else
			error_message = "this keyword already exist!";
	else
		error_message = "cannot be over eight keywords!";
	if (!return_value) {
		return {
			value : false,
			errorMessage : error_message
		};
	}
	return {
		value : true,
		errorMessage : ""
	};
}

function notOverEight(priority) {
	var n = parseInt(priority);
	if (n > 8)
		return false;
	else
		return true;
}

function isPriorityInOrder(priority, editing) {
	if (editing){
		if(priority > Keywords.length) return false;
	}
	var array = [ 0, 0, 0, 0, 0, 0, 0, 0 ];
	var position = parseInt(priority)-1;
	array[position]++;
	for ( var i = 0; i < Keywords.length; i++) {
		var element = Keywords[i];
		position = parseInt(element.priority) - 1;
		array[position]++;
	}
	var end = false;
	for (var i = 0; i < array.length; i++) {
		if (array[i] == 0)
			end = true;
		if (end && array[i] > 0)
			return false;
	}
	return true;
}

function areThereDoubles(keyword, oldKeyword) {
	if (oldKeyword == undefined) { // if we are adding new keyword
		for ( var i = 0; i < Keywords.length; i++) {
			var element = Keywords[i];
			if (element.keyword == keyword)
				return false;
		}
		return true;
	} else { // if we are editing existing one
		for ( var i = 0; i < Keywords.length; i++) {
			var element = Keywords[i];
			if (element.keyword != oldKeyword)
				if(element.keyword == keyword) return false;
		}
		return true;
	}
}

// within this function we use HTTP POST request to put a new keyword on server
// format of the message should be following {“id”:”user’s id”,
// “priority”:”keyword’s priority”,“keyword”:”new keyword”}
// there is no response to this request

function addNewKeywordOnServer(keywordMessage) {
	sendSimpleCUDKeywordRequest("POST", keywordMessage);
}

function editKeyword(priority, keyword, old_keyword) {
	deleteOneKeyword(getPriorityByKeyword(old_keyword));
	arrangeKeywords(priority, function(prior) {
		var newPrior = parseInt(prior) + 1;
		return newPrior.toString();
	});
	Keywords.push( {
		priority : priority,
		keyword : keyword
	});
	var message = objectToJson(new UpdateKeyword(old_keyword, priority, keyword));
	editKeywordOnServer(message);
}

// within this function we use HTTP PUT request to change an existing keyword on
// server
// format of the message should be following {“id”:”user’s id”, “oldKeyword”:
// “oldKeyword”, {“priority”:”keyword’s priority”,“keyword”:”changed keyword”}}
// there is no response to this request

function editKeywordOnServer(keywordMessage) {
	sendSimpleCUDKeywordRequest("PUT", keywordMessage);
}

// function deletes one keyword (by priority) from Keywords array
function deleteOneKeyword(priority) {
	var k = new Array();
	var index = 0;
	for ( var i = 0; i < Keywords.length; i++) {
		var keyword = Keywords[i];
		if (keyword.priority != priority) {
			if (keyword.priority > priority) {
				var newPrior = parseInt(keyword.priority) - 1;
				k.push( {
					priority : newPrior.toString(),
					keyword : keyword.keyword
				});
			} else {
				k.push( {
					priority : keyword.priority,
					keyword : keyword.keyword
				});
			}
			index++;
		}
	}
	Keywords = k;
}

function deleteKeyword(priority) {
	var keyword = Keywords[priority - 1].keyword;
	deleteOneKeyword(priority);
	var message = objectToJson(new DeleteKeyword(keyword));
	deleteKeywordOnServer(message);
}

// within this function we use HTTP DELETE request to delete keyword on server
// format of the message should be following {“id”:”user’s id”,“keyword”:
// “keywordToDelete”}
// there is no response to this request

function deleteKeywordOnServer(keywordMessage) {
	sendSimpleCUDKeywordRequest("DELETE", keywordMessage);
}

// as functions for Create, Update and Delete keywords are similar then the
// equal part is
// collected in one function

function sendSimpleCUDKeywordRequest(method, data) {
	var server = serverDomain + "json/keyword"; // server's address
// if (method == "DELETE" || method == "PUT")
// server = "http://161.53.67.206/test/json/keyword2"; // server's address
	var xmlHttpReq = getXMLHttpReqObject();
	xmlHttpReq.open(method, server, true);
	xmlHttpReq.setRequestHeader('Content-Type',
			'application/json; charset=UTF-8');
	xmlHttpReq.send(data);
}